//
//  FSHomeEmailViewController.m
//  WZSOA
//
//  Created by 刘沿 on 16/6/23.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSHomeEmailViewController.h"
#import "GDataDefines.h"
#import "FSFirstModel.h"
#import "FSFirstTableViewCell.h"
#import "MJRefresh.h"

@interface FSHomeEmailViewController ()<UITableViewDataSource,UITableViewDelegate>

- (IBAction)btnClick:(id)sender;

@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIButton *lastbtn;

@property (weak, nonatomic) IBOutlet UIButton *btn1;

@property (weak, nonatomic) IBOutlet UIButton *btn2;

@property (weak, nonatomic) IBOutlet UIButton *btn3;

@property (weak, nonatomic) IBOutlet UIButton *btn4;

@property (nonatomic,assign) NSInteger index;

@end

@implementation FSHomeEmailViewController

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }

    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"收件箱";
    
    self.currentPage = 1;
    
    UITableView *tab = [[UITableView alloc] init];
    
    tab.delegate = self;
    
    tab.dataSource = self;
    
    self.tableView = tab;
    
    [self.view addSubview:tab];

    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).mas_offset(110);
        
        make.left.equalTo(self.view.mas_left).mas_offset(20);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-20);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(-20);
        
    }];
    
    __weak typeof (self) weakSelf = self;
    
    self.lastbtn = self.btn1;
    
    [self.btn1 setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    [self.btn2 setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    [self.btn3 setTitleColor:[UIColor redColor] forState:UIControlStateSelected];

    self.btn1.selected = YES;
    
    [self.tableView addHeaderWithCallback:^{
        
        weakSelf.currentPage = 1;
        
        [weakSelf loadMore:weakSelf.lastbtn];
        
    }];
    [tab headerBeginRefreshing];
    
    [tab addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
            
            [weakSelf loadMore:self.lastbtn];
            
            [weakSelf.tableView footerEndRefreshing];

        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
            
        }
        
    }];
}

//按钮点击事件

- (IBAction)btnClick:(id)sender {
    
    self.currentPage = 1;
    
    UIButton *btn = (UIButton *)sender;
    
    btn.selected = YES;
    
    
    if (self.lastbtn != btn) {
        self.lastbtn.selected = NO;

        [self.dataArray removeAllObjects];

    }
    
    self.lastbtn = btn;
    
    NSString *method = nil;
    NSString *url = nil;
    
    if (btn.tag == 100) {
//收件箱
        method = KoutboxPage;
        
        url = KexchmailURL;
        
        self.index = 1;
        
        self.title = @"收件箱";
        self.navigationItem.rightBarButtonItem = nil;

    }else if(btn.tag == 101){
//发件箱
        method = KmailPage;
        
        url = KexchmailURL;
    
        self.index = 2;
        
        self.title = @"发件箱";
        
//新建邮箱按钮
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(newEmail)];
        
        self.navigationItem.rightBarButtonItem = item;
        
    }else if(btn.tag == 102){
    
//草稿箱
        self.index = 2;
        url = KexchmailURL;

        method = KdraftsPage;
        
        self.title = @"草稿箱";
        self.navigationItem.rightBarButtonItem = nil;

    }else {
//垃圾箱
        self.index = 2;
        url = KexchmailURL;

        method = KdustbinPage;
        
        self.title = @"垃圾箱";
        self.navigationItem.rightBarButtonItem = nil;

    }
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:url arrays:array method:method success:^(id JSON) {

        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        
//        if (self.lastbtn != btn) {
//            
//            self.currentPage++;
//        
//        }
//        
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
        
    }];
    
}

#pragma mark -----  新建邮件
- (void)newEmail{

    OANewEmailController * newEmailVC = (OANewEmailController*)[self.storyboard instantiateViewControllerWithIdentifier:@"NewEmailVCID"];
    newEmailVC.type = Other;
    [self.navigationController pushViewController:newEmailVC animated:YES];
    
}

- (void)loadMore:(UIButton *)btn{
    NSString *method = nil;
    NSString *url = nil;
    
    if (btn.tag == 100) {
        //收件箱
        method = KoutboxPage;
        
        url = KexchmailURL;
        
    }else if(btn.tag == 101){
        //发件箱
        method = KmailPage;
        
        url = KexchmailURL;
        
    }else if(btn.tag == 102){
        
        //草稿箱
        
        url = KexchmailURL;
        
        method = KdraftsPage;
    }else {
        //垃圾箱
        url = KexchmailURL;
        
        method = KdustbinPage;
    }
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
     NSArray * array = @[@{@"userId":userID},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    
    [HttpTools postWithURL:url arrays:array method:method success:^(id JSON) {
    
        if (self.currentPage == 1) {
            
            [self.dataArray removeAllObjects];
            
        }
        
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage ++;
        
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        
        [self.tableView headerEndRefreshing];
        
    }];
    
}



//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSFirstModel * model = [[FSFirstModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"发送时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            GDataXMLElement * isReadElement = [[data elementsForName:@"是否已读"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            model.isRead = [isReadElement stringValue];
            model.iconType = @"InBox"; //发送箱
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    
    return array;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSFirstModel * model = self.dataArray[indexPath.row];
    CGFloat height = 0;
    CGFloat  titlesize  = [FSHightTool heightbyString:model.title font:15 minsWidth:0];
//        NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
//        CGFloat dessize = [FSHightTool heightbyString:desstring font:15 minsWidth:0];
    height = titlesize + 50;
    return  height;
}


#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSFirstTableViewCell * cell = [FSFirstTableViewCell FirstTableViewCell];
    FSFirstModel * model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FSFirstModel * model = self.dataArray[indexPath.row];

    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
//收件箱详情
    FSEmailReceiveDetailController *emailDetail = [sb instantiateViewControllerWithIdentifier:@"EmailReceiveDetailVC"];
    emailDetail.index = self.index;
    
    emailDetail.fileId = model.fileId;
    
    [self.navigationController pushViewController:emailDetail animated:YES];


}


@end
























